package com.link.play.fit.ai.ui.dialog

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import com.link.play.fit.ai.R
import com.link.play.fit.ai.databinding.DialogCongratulationBinding
import com.link.play.fit.ai.utils.BitmapUtils.saveBitmapToUri
import com.link.play.fit.ai.utils.ScreenUtil.Companion.dpToPx
import kotlinx.coroutines.launch
import nl.dionsegijn.konfetti.core.Party
import nl.dionsegijn.konfetti.core.Position
import nl.dionsegijn.konfetti.core.emitter.Emitter
import java.util.concurrent.TimeUnit
import kotlin.math.abs


class CongratulationDialog(
    val activity: AppCompatActivity
) {
    private val TAG = "CongratulationDialog"
    private val dialog = AlertDialog.Builder(activity).create()
    private val binding = DialogCongratulationBinding.inflate(LayoutInflater.from(activity))

    @SuppressLint("StringFormatMatches")
    fun showDialog(imperialMetric: Boolean, changeValue: Int, currentWeight: Int) {
        dialog.setView(binding.root)
        dialog.setCanceledOnTouchOutside(true)
        dialog.setCancelable(true)
        dialog.show()

        dialog?.window?.setBackgroundDrawableResource(R.color.transparent)
        val params = dialog?.window?.attributes
        params?.width = ConstraintLayout.LayoutParams.MATCH_PARENT
        params?.gravity = Gravity.BOTTOM

        dialog?.window?.attributes = params

        var s = ""
        if (imperialMetric) {
            if (changeValue > 0) {
                s = activity.getString(R.string.you_ve_gain_kg, abs(changeValue))
            } else {
                s = activity.getString(R.string.you_ve_lost_kg, abs(changeValue))
            }
        } else {
            if (changeValue > 0) {
                s = activity.getString(R.string.you_ve_gain_lbs, abs(changeValue))
            } else {
                s = activity.getString(R.string.you_ve_lost_lbs, abs(changeValue))
            }
        }
        binding.tvChange.text = s
//        var tag = true
//        fun tickFlow(intervalMs: Long = Random.nextLong(1000, 1500)): Flow<Unit> = flow {
//            while (tag) {
//                emit(Unit) // 发射一个值（Unit 表示无实际意义的值）
//                delay(intervalMs) // 延迟 200ms
//            }
//        }

//        val job = MainScope().launch {
//            tickFlow().collectLatest {
        val party = Party(
            speed = 0f,
            maxSpeed = 30f,
            damping = 0.9f,
            spread = 360,
            colors = listOf(0xfce18a, 0xff726d, 0xf4306d, 0xb48def),
            position = Position.Relative(0.5, 0.3),
            emitter = Emitter(duration = 100, TimeUnit.MILLISECONDS).max(100),
        )
        binding.konfettiView.reset()
        binding.konfettiView.start(party)
//            }
//        }
        binding.tvValue.text = currentWeight.toString()
        binding.tvTip.text = activity.getString(R.string.your_efforts_are_reshaping, activity.getString(R.string.app_name))
        dialog.setOnDismissListener {

        }

        binding.ivClose.setOnClickListener {
            dialog.dismiss()
        }

        binding.llMessages.setOnClickListener {

            activity.lifecycleScope.launch {

                val bitmap: Bitmap? = generateShareImage(activity, s, currentWeight)
                if (bitmap == null) {
                    // 显示错误提示
                    Toast.makeText(activity, "Share Message error", Toast.LENGTH_SHORT).show()
                    return@launch
                }

                val imageUri: Uri = saveImageToFile(activity, bitmap)

                val intent = Intent(Intent.ACTION_SEND)
                intent.putExtra(Intent.EXTRA_STREAM, imageUri)
                intent.setType("image/png")

                try {
                    val resolveActivity = Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"))
                        .resolveActivity(activity.packageManager)
                    if (resolveActivity != null) {
                        intent.setPackage(resolveActivity.packageName)
                    }
                    activity.startActivity(intent)
                } catch (e: Exception) {
                    Toast.makeText(activity, "no app support!", Toast.LENGTH_SHORT).show()
                }
            }
        }

        binding.llCopy.setOnClickListener {
            activity.lifecycleScope.launch {
                val bitmap: Bitmap? = generateShareImage(activity, s, currentWeight)
                if (bitmap == null) {
                    // 显示错误提示
                    Toast.makeText(activity, "Share Message error", Toast.LENGTH_SHORT).show()
                    return@launch
                }
                val imageUri: Uri = saveImageToFile(activity, bitmap)

                // 复制图片URI到剪贴板
                val clipboard: ClipboardManager = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                clipboard.setPrimaryClip(ClipData.newUri(activity.contentResolver, "Image", imageUri))

                // 显示成功提示
                Toast.makeText(activity, "share copy success", Toast.LENGTH_SHORT).show()

            }
        }

        binding.llOther.setOnClickListener {
            activity.lifecycleScope.launch {
                val bitmap: Bitmap? = generateShareImage(activity, s, currentWeight)
                if (bitmap == null) {
                    // 显示错误提示
                    Toast.makeText(activity, "Share Message error", Toast.LENGTH_SHORT).show()
                    return@launch
                }

                val imageUri: Uri = saveImageToFile(activity, bitmap)

                val intent = Intent(Intent.ACTION_SEND)
                intent.setType("image/png")
                intent.putExtra(Intent.EXTRA_STREAM, imageUri)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                try {
                    activity.startActivity(Intent.createChooser(intent, "Share Image"))
                } catch (e: Exception) {
                    Toast.makeText(activity, "no app support!", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }


}

private fun saveImageToFile(activity: Activity, bitmap: Bitmap): Uri {
    return saveBitmapToUri(bitmap, activity) ?: Uri.EMPTY
}

@SuppressLint("WrongConstant", "MissingInflatedId")
fun generateShareImage(activity: Activity, s: String, currentWeight: Int): Bitmap? {
    // ... 前置处理逻辑（如协程恢复、状态检查等） ...

    // 使用 LayoutInflater 加载自定义视图（比如成就分享页面）
    val view = LayoutInflater.from(activity).inflate(R.layout.item_share_image, null);
    view.findViewById<TextView>(R.id.tvChange).text = s
    view.findViewById<TextView>(R.id.tv22).text =
        activity.getString(R.string.your_efforts_are_reshaping, activity.getString(R.string.app_name))
    view.findViewById<TextView>(R.id.tvValue).text = currentWeight.toString()

    val w = dpToPx(343f).toInt()
    val h = dpToPx(520f).toInt()

    // 测量和布局视图（离屏处理，不显示在 UI 上）
//    view.measure(
//        View.MeasureSpec.makeMeasureSpec(0, 0),
//        View.MeasureSpec.makeMeasureSpec(0, 0)
//    )
//    view.layout(0, 0, view.measuredWidth, view.measuredHeight);
    view.measure(
        View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY),
        View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY)
    )
    view.layout(0, 0, w, h)

    // 创建位图（Bitmap）并将视图内容绘制进去
    val bitmap: Bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888);
    view.draw(Canvas(bitmap))

    // 返回生成的位图
    return bitmap
}
